package com.beiding.workordersystem.common.utils;

import org.apache.xmlbeans.impl.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class Encipher {

    //秘钥
    private static final byte[] key = new byte[]{-128, 52, 1, 121, 31, -83, 2, -75};

    private static final SecretKey secretKey;

    private static final Cipher cipher;
    private static final Cipher cipherDecode;

    static {
        secretKey = new SecretKeySpec(key, "DES");
        try {
            cipherDecode = Cipher.getInstance("DES");
            cipherDecode.init(Cipher.DECRYPT_MODE, secretKey);
            cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            throw new Error(e);
        }
    }

    public static String encrypt(String s) {
        if (s == null) {
            return null;
        }
        try {
            byte[] bytes = cipher.doFinal(s.getBytes());
            return byteArrayToString(bytes);
        } catch (Exception ignore) {
            return null;
        }
    }


    public static String decrypt(String code) {
        if (code == null) {
            return null;
        }
        try {
            byte[] bytes = stringToByteArray(code);
            return new String(cipherDecode.doFinal(bytes));
        } catch (Exception ignore) {
            return null;
        }
    }

    private static Map<Byte, String> charMap = new HashMap<>();
    private static Map<String, Byte> byteMap = new HashMap<>();

    static {
        for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
            int k = i + 128;
            int c = k / 26;
            char f = (char) (c + 'A');
            char s = (char) (k - c * 26 + 'a');
            String d = f + "" + s;
            charMap.put((byte) i, d);
            byteMap.put(d, (byte) i);
        }
    }

    public static String byteArrayToString(byte[] arr) {
        StringBuilder builder = new StringBuilder();
        for (byte b : arr) {
            builder.append(charMap.get(b));
        }
        return builder.toString();
    }

    public static byte[] stringToByteArray(String string) {
        char[] chars = string.toCharArray();
        byte[] bs = new byte[chars.length / 2];
        for (int i = 0; i < bs.length; i++) {
            int k = i * 2;
            String s = string.substring(k, k + 2);
            bs[i] = byteMap.get(s);
        }
        return bs;
    }

}
